package com.ophiux.demo.subscribe;

import lombok.experimental.UtilityClass;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

/**
 * @desc: 取消订阅
 * @author: hhl
 * @date：2023/12/15 10:40
 */
@UtilityClass
public class UnSubscribeSample {


    public static void main(String[] args) {
        unSubscribe();
    }


    public void unSubscribe(){
        String broker = "tcp://broker.emqx.io:1883";
        String topic = "hhltest";
        String username = "emqx";
        String password = "public";
        String clientid = "mqttx_c0b664822";
        int qos = 0;

        try {
            MqttClient client = new MqttClient(broker, clientid, new MemoryPersistence());
            // 连接参数
            MqttConnectOptions options = new MqttConnectOptions();
            options.setUserName(username);
            options.setPassword(password.toCharArray());
            options.setConnectionTimeout(600);
            options.setKeepAliveInterval(60);
            options.setAutomaticReconnect(true);
            // 设置回调
            client.connect(options);

            //接收消息
            client.unsubscribe(topic);
            System.out.println("UnSubscribed to topic: " + topic);

            //断开连接
//            client.disconnect();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
